import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
})

// request interceptor
service.interceptors.request.use(config => {
  const token = store.getters.token
  // console.log(15, token)
  // 如果有token才进行下面的判断
  // console.log(17, config)
  // if (config.method !== 'get' && !config.url.includes('/auth/')) {
  //   config.headers.Authorization = token
  // }
  // if (config.method === 'get' && config.url.includes('/roles')) {
  //   config.headers.Authorization = token
  // }
  // if (config.method === 'get' && config.url.includes('/users')) {
  //   config.headers.Authorization = token
  // }
  // if (config.method === 'get' && config.url.includes('permissions')) {
  //   config.headers.Authorization = token
  // }
  if (token && !config.url.includes('/auth/local/register')) {
    // token 超时
    const loginTime = localStorage.getItem('loginTime')
    const timeout = 1000 * 60 * 60 * 2
    const now = Date.now()
    const isTimeOut = now - loginTime > timeout
    // if (now - time > 5000) {
    // // 代表token超时，强行返回登录页面
    //   return Promise.reject(new Error('token超时'))
    // }
    if (isTimeOut) {
      localStorage.removeItem('fc-token')
      localStorage.removeItem('user')
      localStorage.removeItem('fc-perms')
      location.href = '/login'
      // Message.error('登录超时,请重新登录')
      return Promise.reject(new Error('登录超时,请重新登录!'))
    }
    // token封装
    config.headers.Authorization = token
  }
  return config
},
error => {
  console.log(error)
  return Promise.reject(error)
}
)

// response interceptor
service.interceptors.response.use(response => {
  if (response.status !== 200) {
    // console.log(45, response.status)
    Message({
      message: response.statusText || 'Error',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(new Error(response.statusText || 'Error'))
  } else {
    return response
  }
},
error => {
  console.log('err' + error) // for debug
  Message({
    message: error.message,
    type: 'error',
    duration: 5 * 1000
  })
  return Promise.reject(error)
}
)

export default service
